package cn.cucc.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import cn.hutool.core.util.StrUtil;

@Component
public class SqlUtils {
	Logger logger = LoggerFactory.getLogger(this.getClass());

	@Value("${spring.datasource.url:}")
	String url;

	@Value("${spring.datasource.printsql:true}")
	Boolean printsql;

	String separator = System.getProperty("line.separator");

	public void logQuery(String sql) {
		logQuery(sql, null);
	}

	public void logQuery(String sql, Object[] params) {
		sql = formatSql(sql);

		if (params != null) {
			for (Object object : params) {

				if (object instanceof String) {
					sql = sql.replaceFirst("\\?", "'" + object.toString().replace("$", "¥").replace("\\%", "\\\\%") + "'");
				} else {
					sql = sql.replaceFirst("\\?", String.valueOf(object));
				}

			}
		}
		if (printsql) {
			logger.info(separator + sql + separator);
		}
	}

	public String formatSql(String sql) {
		if (StrUtil.isEmpty(sql)) {
			return "";
		}

		if (!url.contains("mysql")) {
			sql = sql.replace("`", "\"");
		}

		sql = sql.replace("FROM", separator + "FROM")//
				.replace("WHERE", separator + "WHERE")//
				.replace("ORDER", separator + "ORDER")//
				.replace("LIMIT", separator + "LIMIT")//
				.replace("VALUES", separator + "VALUES");//
		return sql;
	}
}
